//taro
import { Cell } from "@nutui/nutui-react-taro";
import { ArrowRight } from "@nutui/icons-react-taro";

//react
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  changeUser,
  changeWxInfo,
  myWxInfo,
  phoneOpenid,
  // storeMember_id,
  storeUser,
} from "@/redux/userSlice";

// taro
import Taro, { useShareAppMessage } from "@tarojs/taro";
import { View } from "@tarojs/components";

import dayjs from "dayjs";
import wxImg from "../../assets/wx.jpg";
import "./index.scss";

import homeImg from "../../assets/home.jpg";

// utils
import { ApiCheckLogin, ApiLogout, ApiMemberInfo } from "@/utils/api";

const reInfo = () => {
  useShareAppMessage((res) => {
    if (res.from === "button") {
      // 来自页面内转发按钮
      console.log(res.target);
    }

    return {
      title: "东进会员",
      path: "pages/home/index", //?id=123
      imageUrl: homeImg,
    };
  });
  // const storeMemberId = useSelector(storeMember_id);
  const dispatch = useDispatch();
  const user = useSelector(storeUser);
  const myOpenid = useSelector(phoneOpenid);
  const wxInfo = useSelector(myWxInfo);

  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // loading
  const [loading, setLoading] = useState(true);
  // 用户填写信息
  const [formData, setFormData] = useState({
    name: "",
    sex: 0,
    birthday: null,
    mobile: "",
    captcha: "",
    plate_number: "",
    // member: member,
    member_car_plate_number: "",
  });

  const checkLogin = async () => {
    if (!myOpenid) {
      // 去到注册页
      Taro.reLaunch({
        url: "/pages/home/index",
      });
    }
    console.log(myOpenid, "openid");
    // console.log(formData, "formData");
    // 暂时先用手机号+
    const res = await ApiCheckLogin(myOpenid);
    if (res.code == 0) {
      // 当前页面使用
      setMember_id(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      // 用于后续 获取会员详情信息
      console.log(res.data.member_id);
      await getMemberInfo(res.data.member_id);
      return res.data.member_id;
    } else if (res.code == 2001) {
      await ApiLogout();
      await checkLogin();
      console.warn("ApiCheckLogin失败");
      Taro.showToast({
        title: res.msg || '失败',
        icon: "error",
      });
      setTimeout(()=>{
        Taro.reLaunch({
          url: "/pages/home/index",
        });
      },500)
    } else {
      console.warn("未登录");
      Taro.showToast({
        title: res.msg || "失败",
        icon: "error",
      });
      setTimeout(() => {
        Taro.reLaunch({
          url: "/pages/home/index",
        });
      }, 500);
      return;
    }
  };

  // 修改user对象属性值
  const handleFieldChange = <K extends keyof RootObject>(
    fieldName: K,
    value: RootObject[K]
  ) => {
    // console.log(fieldName, value);
    setFormData((prevData) => ({
      ...prevData,
      [fieldName]: value,
    }));
  };

  //  user对象里的属性名 属性值
  const handleNameInputChange = (
    type: keyof RootObject,
    value: RootObject[keyof RootObject]
  ) => {
    // console.log("type", type);
    handleFieldChange(type, value);
    // form.setFieldsValue(formData);
    // console.log("formData", formData);
  };

  // 获取会员详情信息
  const getMemberInfo = async (member_id2?: number) => {
    let my_member_id = member_id2 ? member_id2 : member_id;
    // console.log(my_member_id, "my_member_id");
    if (!myOpenid) {
      console.log("需重新进入");
      Taro.reLaunch({
        url: "/pages/home/index",
      });
      return;
    }
    // console.log(my_member_id, "my_member_id");
    // 请求用户信息

    // 校验是否有
    let resInfo;
    console.log(user, "user");
    if (!user.mobile) {
      try {
        console.log(user.mobile, "mobile");
        resInfo = await ApiMemberInfo(my_member_id);
      } catch (error) {
        resInfo = error;
          // Handle the error here
        console.error("An error occurred:", error);
        Taro.reLaunch({
          url: "/pages/home/index",
        });
      } finally {
        // 无论请求成功或失败，都设置 loading 为 false
        // 使用骨架屏
        setLoading(false);
      }
      // console.log(resInfo, "resInfo");
      if (resInfo.code != 0) {
        console.log("请求用户信息失败");
        // 重新请求
        Taro.reLaunch({
          url: "/pages/home/index",
        });
        return;
      }
        // 没有请求,存仓库
      dispatch(changeUser(resInfo.data));
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = resInfo.data;
      const phone = mobile.replace(/(\d{3})\d+(\d{4})/, "$1****$2");
      // console.log(birthday, "birthday");
      
      // 更新
      handleNameInputChange("name", name);
      handleNameInputChange("mobile", phone);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "前往绑定车牌号"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      birthday &&
        handleNameInputChange(
          "birthday",
          new Date(birthday.replace(/-/g, "/"))
        );
    } else {
      setLoading(false);
      // 从仓库读取
      // console.log(user, "user");
      // 更新用户对象
      const {
        name,
        mobile,
        sex,
        birthday,
        member_car_plate_number,
        created_at,
        free_parking_expire_at,
      } = user;
      const phone = mobile.replace(/(\d{3})\d+(\d{4})/, "$1****$2");
      console.log(birthday, "birthday");

      handleNameInputChange("name", name);
      handleNameInputChange("mobile", phone);
      handleNameInputChange("sex", sex);
      handleNameInputChange(
        "member_car_plate_number",
        member_car_plate_number || "前往绑定车牌号"
      );
      handleNameInputChange("created_at", created_at);
      handleNameInputChange("free_parking_expire_at", free_parking_expire_at);
      birthday && handleNameInputChange("birthday", new Date(birthday.replace(/-/g, "/")));
    }
    // form.setFieldsValue(formData);
    return resInfo;
  };

  // 在页面加载时从localStorage获取图像数据
  const initialImg = Taro.getStorageSync("img") || "";
  const [img, setImg] = useState<string>(initialImg);

  // 修改用户信息
  const changeInfo = () => {
    Taro.navigateTo({
      url: "/pages/infochange/index",
    });
  };
  // 修改头像
  const changeInfo2 = () => {
    // 触发文件选择器
    Taro.chooseImage({
      success: (res) => {
        const selectedImg = res.tempFilePaths[0];
        setImg(selectedImg);
        Taro.setStorageSync("img", selectedImg);
        // 
        dispatch(changeWxInfo({ ...wxInfo, avatarUrl: selectedImg }));
      },
    });
  };
  // 修改手机号
  const changePhone = () => {
    Taro.navigateTo({
      url: "/pages/phone/index",
    });
  };

  // 挂载页面
  useEffect(() => {
    getMemberInfo();
  }, []);
  // 挂载页面

  return (
    <View>
      <View>
        <View className="big_box">
          {/* 中间卡片 */}
          <View className="List_box" onClick={() => {}}>
            <Cell.Group
              title="会员信息"
              style={{ display: !loading ? "block" : "none" }}
            >
              <Cell
                title="头像"
                onClick={changeInfo2}
                extra={
                  <>
                    <View className="img">
                      <input
                        className="input"
                        type="file"
                        id="headImg"
                        hidden
                      />
                      <label htmlFor="headImg" className="headImg">
                        <View
                          className="headImg"
                          id="headImg"
                          style={{ backgroundImage: `url(${img || wxImg})` }}
                        ></View>
                      </label>
                    </View>
                    <ArrowRight color="#ccc" />
                  </>
                }
              ></Cell>
              <Cell
                title="姓名"
                extra={
                  <>
                    <span>{formData.name}</span>
                    <ArrowRight color="#ccc" />
                  </>
                }
                onClick={changeInfo}
              ></Cell>
              <Cell
                title="性别"
                extra={
                  <>
                    <span>
                      {formData.sex == 1
                        ? "男"
                        : formData.sex == 2
                        ? "女"
                        : "未知"}
                    </span>
                    <ArrowRight color="#ccc" />
                  </>
                }
                onClick={changeInfo}
              ></Cell>
              <Cell
                title="手机号"
                extra={
                  <>
                    <span>{formData.mobile}</span>
                    <ArrowRight color="#ccc" />
                  </>
                }
                onClick={changePhone}
              ></Cell>
              <Cell
                title="出生日期"
                extra={
                  <>
                    <span>
                      {formData.birthday
                        ? dayjs(formData.birthday).format("YYYY-MM-DD")
                        : "请选择日期"}
                    </span>
                    <ArrowRight color="#ccc" />
                  </>
                }
                onClick={changeInfo}
              ></Cell>
              <Cell
                title="车牌号"
                extra={
                  <>
                    <span>{formData.member_car_plate_number}</span>
                    <ArrowRight color="#ccc" />
                  </>
                }
                onClick={() =>
                  Taro.navigateTo({
                    url: "/pages/member/index",
                  })
                }
              ></Cell>
            </Cell.Group>
          </View>
        </View>
      </View>
    </View>
  );
};

export default reInfo;
